/**
 * Created by 烈日影视 on 2018/3/29.
 */
function ismobile() {
    //判断访问终端
    var browser = {
        versions: function () {
            var u = navigator.userAgent, app = navigator.appVersion;
            return {
                trident: u.indexOf('Trident') > -1, //IE内核
                presto: u.indexOf('Presto') > -1, //opera内核
                webKit: u.indexOf('AppleWebKit') > -1, //苹果、谷歌内核
                gecko: u.indexOf('Gecko') > -1 && u.indexOf('KHTML') == -1,//火狐内核
                mobile: !!u.match(/AppleWebKit.*Mobile.*/), //是否为移动终端
                ios: !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/), //ios终端
                android: u.indexOf('Android') > -1 || u.indexOf('Adr') > -1, //android终端
                iPhone: u.indexOf('iPhone') > -1, //是否为iPhone或者QQHD浏览器
                iPad: u.indexOf('iPad') > -1, //是否iPad
                webApp: u.indexOf('Safari') == -1, //是否web应该程序，没有头部与底部
                weixin: u.indexOf('MicroMessenger') > -1, //是否微信 （2015-01-22新增）
                qq: u.match(/\sQQ/i) == " qq" //是否QQ
            };
        }(),
        language: (navigator.browserLanguage || navigator.language).toLowerCase()
    };
    if (browser.versions.mobile == true) {
        if (browser.versions.iPhone == true) {
            return '1';
        } else if (browser.versions.android == true) {
            return '0';
        }
    } else {

    }
};

//$(function () {
//
//    getOrderId();

var totalPrice, useCoupon, token, address;

//nextAjax({
// "TOKEN": "D862733A-2790-5B20-2441-31BC86415241",
// "need_addr": "海淀区",
// "uid": 30,
// "goods_id": 8,
// "meal": { "name": "商品测试名称", "data_type": "2388", "id": 0 },
// "startTime": "2017-12-27 12:30",
// "endTime": "2018-01-27 16:30",
// "money": "4500"
// })
//});
var isMobile = ismobile();

function getOrderId() {

    if (isMobile == 1) {

        CallManPowerListModel.jsCallOCWithSendId("ok");

    } else if (isMobile == 0) {

        window.android.getAndroidOrderId("okok");
    }
}

if (isMobile == 0) {

    window.android.getAndroidOrderId("okok");
}

function WebViewDidFinishLoad() {

    var message = {

        "VcWay": "SendId"
    };

    window.webkit.messageHandlers.CallManPowerListModel.postMessage(message);
}

function receive_android_orderId(k) {

    var obj = $.parseJSON(k);

    //console.log(obj)

    address = obj.need_addr;

    token = obj.TOKEN;

    nextAjax(obj, token, address);

    totalPrice = obj.money;

    useCoupon = 100;

}

function receiveiOSVcData(i) {

    //console.log(i)

    var obj = $.parseJSON(i);
    //console.log(obj)


    //alert(JSON.stringify(obj))

    address = obj.need_addr;

    token = obj.TOKEN;

    nextAjax(obj, token, address);

    totalPrice = obj.money;

    useCoupon = 100;

}

function nextAjax(data_json, token, address) {

    $.ajax({

        type: "POST",

        url: url + "users/goodsinfo",

        data: {

            "goods_id": data_json.goods_id
        },

        dataType: "json",

        success: function (data) {

            var a = Object.assign(data, data_json); //将传递过来的参数拼接在data上

            //console.log(data);

            if (data.codes == 200) {


                var html = template("OrderTpl", data);

                $("#order_body").html(html);

                defaultAddress(data_json.uid);//获取默认地址

                if (isiphoneX) {

                    $("#order_footer").removeClass("order_footer_position");

                    $(".moneyDetail").css("margin-bottom", "0.427rem")

                } else {

                    $("#order_footer").addClass("order_footer_position")
                }


            } else {

                if (isMobile == 1) {

                    window.webkit.messageHandlers.CallManPowerListModel.postMessage({
                        "VcData": "获取数据失败",
                        "VcWay": "ShowMessage"
                    });

                    //CallManPowerListModel.jsCalliOSWithShowMessage("获取数据失败");

                } else if (isMobile == 0) {

                    window.android.toastMsg("获取数据失败");
                }
            }

            //$(".confirmPrice").text(parseInt(data.meal.data_type));

            $(".date").html("日期：" + data.startTime.slice(5) + " ~ " + data.endTime.slice(5));//日期

            var money = totalPrice.slice(1);//商品价格

            var cash_pledge = Number($(".cash_pledge").html());//押金

            // var insurance = parseFloat($(".insurance").html());// 保险

            var couponPrice = Number($(".couponPrice").html()) || 0;//优惠券

            $(".order_price").html("实付款:￥" + (Number(money) + cash_pledge - couponPrice).toFixed(2));//总价

            $(".order_address").on("click", function () { //点击添加地址+号，跳转至添加地址页面

                if (isMobile == 1) {

                    var message = {

                        "VcData": {

                            "contacts": contacts,

                            "iphone": iphone,

                            "addressTitle": address3,

                            "addressDetails": address2
                        },

                        "VcName": "AddressManager",

                        "VcWay": "AddAddress"
                    };

                    window.webkit.messageHandlers.CallManPowerListModel.postMessage(message);

                } else if (isMobile == 0) {

                    var json = {

                        "contacts": contacts,

                        "iphone": iphone,

                        "address": address4,

                        "province": address2,

                        "city": address3
                    };

                    window.android.jumpToProjectAdress(JSON.stringify(json));
                }
            });

            //$(".order_start").html(data.startTime);
            //$(".order_end").html(data.endTime);

            //点击订单中的优惠券，跳转页面并发送参数给ios和安卓
            $(".order_coupon").on("click",  function () {

                var json = {

                    "uid": data.uid,

                    "Tprice": data.money.slice(1),

                    "type": [10, 200]
                };

                if (isMobile == 1) {

                    var message = {

                        "VcData": json,

                        "VcWay": "OrderCoupons"
                    };

                    window.webkit.messageHandlers.CallManPowerListModel.postMessage(message);

                } else if (isMobile == 0) {

                    window.android.showCoupon(JSON.stringify(json));
                }
            });
            //点击订单中的提交订单，跳转支付页面，获取ios和Android的信息
            var flag = true;

            $(".submit").on("click", function () {//检测开始时间    结束时间

                var timeStart = data.startTime.replace(/-/g, "/");

                var timeEnd = data.endTime.replace(/-/g, "/");

                var timestampStart = Date.parse(new Date(timeStart)) / 1000;//开始时间    时间戳

                var timestampEnd = Date.parse(new Date(timeEnd)) / 1000;    //结束时间    时间戳

                var timestampNow = Date.parse(new Date()) / 1000;          //当前时间     时间戳

                //开始时间要大于当前时间  结束时间只能大于开始时间3个月

                var timeLag = timestampEnd - timestampStart;

                var timeDistance = (mGetDate(1) + mGetDate(2) + mGetDate(3)) * 24 * 60 * 60;

                var length = $(".address_phone").html().length;

                //alert(length)

                if (flag && length > 0 && timestampNow < timestampStart && timeLag < timeDistance && timestampEnd > timestampStart) {

                    var cid;

                    if (useCoupon == 100) {

                        ordermake(
                            data.uid,

                            $(".order_price").html().slice(5),

                            $(".address_contacts b").html(),

                            $(".address_phone").html(),

                            $(".serviceAddress b").html(),

                            useCoupon,

                            data.goods_id,

                            1,

                            timeFormatDate(timeStart),

                            timeFormatDate(timeEnd),

                            address,

                            data.meal.id,

                            token,

                            data_json.meal.time_long_id,

                            cid
                        )

                    } else if (useCoupon == 200) {

                        cid = $(".order_coupon").attr("id");//获取优惠券id

                        ordermake(
                            data.uid,

                            $(".order_price").html().slice(5),

                            $(".address_contacts b").html(),

                            $(".address_phone").html(),

                            $(".serviceAddress b").html(),

                            useCoupon,

                            data.goods_id,

                            1,

                            timeFormatDate(timeStart),

                            timeFormatDate(timeEnd),

                            address,

                            data.meal.id,

                            token,

                            data_json.meal.time_long_id,

                            cid
                        )
                    }
                    flag = false;

                    setTimeout(function () {

                        flag = true;

                    }, 1000);//点击后相隔多长时间可执行

                } else {

                    if (timestampStart < timestampNow) {

                        if (isMobile == 1) {

                            window.webkit.messageHandlers.CallManPowerListModel.postMessage({
                                "VcData": "开始时间不能小于当前时间",
                                "VcWay": "ShowMessage"
                            });

                            //CallManPowerListModel.jsCalliOSWithShowMessage("开始时间不能小于当前时间");

                        } else if (isMobile == 0) {

                            window.android.toastMsg("开始时间不能小于当前时间");

                        }
                    } else if (timeLag > timeDistance) {

                        if (isMobile == 1) {

                            window.webkit.messageHandlers.CallManPowerListModel.postMessage({
                                "VcData": "结束时间不能大于开始时间的90天",
                                "VcWay": "ShowMessage"
                            });

                            //CallManPowerListModel.jsCalliOSWithShowMessage("结束时间不能大于开始时间的90天");

                        } else if (isMobile == 0) {

                            window.android.toastMsg("结束时间不能大于开始时间的90天");

                        }
                    } else if (timestampEnd < timestampStart) {//结束时间小于开始时间

                        if (isMobile == 1) {

                            window.webkit.messageHandlers.CallManPowerListModel.postMessage({
                                "VcData": "结束时间不能小于开始时间",
                                "VcWay": "ShowMessage"
                            });

                            //CallManPowerListModel.jsCalliOSWithShowMessage("结束时间不能小于开始时间");

                        } else if (isMobile == 0) {

                            window.android.toastMsg("结束时间不能小于开始时间");

                        }
                    } else if (length <= 0) {

                        if (isMobile == 1) {

                            window.webkit.messageHandlers.CallManPowerListModel.postMessage({
                                "VcData": "服务地址不能为空",
                                "VcWay": "ShowMessage"
                            });

                            //CallManPowerListModel.jsCalliOSWithShowMessage("收货地址不能为空");

                        } else if (isMobile == 0) {

                            window.android.toastMsg("服务地址不能为空");
                        }
                    }

                }

            });

            //点击跳转协议
            //$(".xieyi").on("click", function () {
            //
            //    var json = {
            //        "url": "https://viewapi.aipics.cn/view_h5/agreement/lease.html",
            //
            //        "titleName": "用户租赁协议"
            //    };
            //
            //    if (isMobile == 1) {
            //
            //        var message = {
            //
            //            "VcData": json,
            //
            //            "VcName": "PublicWeb",
            //
            //            "VcWay": "PushVCName"
            //        };
            //
            //        window.webkit.messageHandlers.CallManPowerListModel.postMessage(message);
            //
            //        //CallManPowerListModel.jsCalliOSWithPushVCName({
            //        //
            //        //    "VcData": json, "VcName": "PublicWeb"
            //        //})
            //    } else if (isMobile == 0) {
            //
            //        window.android.toRule(JSON.stringify(json))
            //    }
            //})
        },
        error: function (info) {

            if (isMobile == 1) {

                window.webkit.messageHandlers.CallManPowerListModel.postMessage({
                    "VcData": "请检查网络",
                    "VcWay": "ShowMessage"
                });

                //CallManPowerListModel.jsCalliOSWithShowMessage("请检查网络");

            } else if (isMobile == 0) {

                window.android.toastMsg("请检查网络");
            }
        }
    });
}
//订单收货地址
var address1 = "", address2 = "", address3 = "", address4 = "", contacts = "", contacts1 = "", iphone = "";

//var iphone1 = "";

function receiveiOSAddAddress(a) {

    //console.log(a)

    var result = JSON.parse(a);

    $(".serviceAddress b").html(result['shipping_address']);

    contacts = result['link_man'];

    $(".address_contacts b").html(result['link_man']);

    iphone = result['link_mobile'];

    $(".address").css("margin-left", "0");

    $(".address_phone").html(result['link_mobile']);

}

function receive_android_addAddress(k) {

    //alert(JSON.stringify(k))

    var result = JSON.parse(k);

    //address1 =
    $(".serviceAddress b").html(result.province + result.city + result.district + result.address);

    address2 = result.province;

    address3 = result.city;

    address4 = result.address;

    contacts = result.contacts;

    //contacts1 =

    $(".address_contacts b").html(result.contacts);

    $(".address_phone").html(result.iphone);

    iphone = result.iphone;

    $(".address").css("margin-left", "0");

}

function receiveiOSOrderCoupon(a) {

    var obj = $.parseJSON(a);

    if (obj) {

        useCoupon = 200;

        $(".couponPrice").html(obj.face);

        $(".order_coupon").attr("id", obj.id);

        // alert(useCoupon)

        var money = totalPrice.slice(1);//商品价格

        var cash_pledge = Number($(".cash_pledge").html());//押金

        // var insurance = parseFloat($(".insurance").html());// 保险

        var couponPrice = Number($(".couponPrice").html()) || 0;//优惠券

        $(".couponMoney").html(couponPrice);//优惠金额

        // alert( couponPrice.toFixed(2))

        $(".order_price").html("实付款:￥" + (Number(money) + cash_pledge - couponPrice));//总价

    } else {

        useCoupon = 100;

        $(".couponPrice ").html("请选择");

    }
}

function receive_android_orderCoupon(k) {

    var obj = $.parseJSON(k);

    if (obj) {

        useCoupon = 200;

        $(".couponPrice").html(obj.face);

        $(".order_coupon").attr("id", obj.cid);

        //alert($(".order_coupon").attr("id"))

        var money = totalPrice.slice(1);//商品价格

        var cash_pledge = Number($(".cash_pledge").html());//押金

        // var insurance = parseInt($(".insurance").html());// 保险

        var couponPrice = Number($(".couponPrice").html()) || 0;//优惠券

        $(".couponMoney").html(couponPrice);//优惠金额

        // alert( couponPrice.toFixed(2))

        $(".order_price").html("实付款:￥" + (Number(money) + cash_pledge - couponPrice));//总价

    } else {

        useCoupon = 100;

        $(".couponPrice").html("请选择");

        // alert(useCoupon)
    }
}
//格式化时间
function timeFormatDate(timeStamp) {

    var tmpTime = Date.parse(new Date(timeStamp));

    Date.prototype.format = function (format) {
        var date = {
            "M+": this.getMonth() + 1,
            "d+": this.getDate(),
            "h+": this.getHours(),
            "m+": this.getMinutes(),
            "s+": this.getSeconds(),
            "q+": Math.floor((this.getMonth() + 3) / 3),
            "S+": this.getMilliseconds()
        };
        if (/(y+)/i.test(format)) {
            format = format.replace(RegExp.$1, (this.getFullYear() + '').substr(4 - RegExp.$1.length));
        }
        for (var k in date) {
            if (new RegExp("(" + k + ")").test(format)) {
                format = format.replace(RegExp.$1, RegExp.$1.length == 1
                    ? date[k] : ("00" + date[k]).substr(("" + date[k]).length));
            }
        }
        return format;
    };

    var newDate = new Date();

    newDate.setTime(tmpTime);

    return newDate.format('yyyyMMddhhmm');
}

function defaultAddress(uid) {

    $.ajax({

        url: url + "users/fourModel",

        type: "POST",

        dataType: "json",

        data: {

            "url": "address/lists",

            "uid": uid,

            "addr_type": 1

        },

        success: function (data) {

            //alert(JSON.stringify(data))

            if (data.codes == 200) {

                var list = data.data.list[0];

                $(".address_contacts b").html(list.link_man);

                $(".address_phone").html(list.link_mobile);

                $(".serviceAddress b").html(list.shipping_address);

                //$(".address .defultaddr").css("display", "block");//默认地址显示

                //$(".order_address").attr("data-type", "100");


                $(".address").css("margin-left", "0")

            } else {

                //$(".order_address").attr("data-type", "200");

                //$(".address .defultaddr").css("display","none");

            }
        },
        error: function (info) {

            if (isMobile == 1) {

                window.webkit.messageHandlers.CallManPowerListModel.postMessage({
                    "VcData": "地址获取失败",
                    "VcWay": "ShowMessage"
                });

                //CallManPowerListModel.jsCalliOSWithShowMessage("地址获取失败");

            } else if (isMobile == 0) {

                window.android.toastMsg("地址获取失败");
            }
        }
    });
}
//获取当前月的天数，下月，下下月的总和
function mGetDate(n) {

    var date = new Date();

    var year = date.getFullYear();

    var month = date.getMonth() + n;

    if (month > 12) {

        year++;

        month = month - 12;
    }
    var d = new Date(year, month, 0);

    return d.getDate();
}
//下单
function ordermake(uid, total_money, receive_user_name, receive_user_mobile, receive_user_addr, useCoupon, goods_id, need_number, start_time, end_time, need_addr_id, meal_id, token, time_long_id, cid) {

    //alert(uid+"--"+ total_money+"--"+ receive_user_name+"--"+receive_user_mobile+"--"+receive_user_addr+"--"+ useCoupon+"--"+ goods_id+"--"+ need_number+"--"+ start_time+"--"+end_time+"--"+ need_addr_id+"--"+ meal_id+"--"+ token+"--"+ time_long_id+"--"+ cid);

    $.ajax({

        type: "POST",

        url: url + "users/ordermake",

        dataType: "json",

        data: {

            "uid": uid,

            "total_money": total_money,

            "receive_user_name": receive_user_name,

            "receive_user_mobile": receive_user_mobile,

            "receive_user_addr": receive_user_addr,

            "use_coupon": useCoupon,//默认不使用 值为100

            "coupon_id": cid,

            "order_info": [
                {
                    "goods_id": goods_id,

                    "need_number": need_number,

                    "start_time": start_time,

                    "end_time": end_time,

                    "need_addr_id": need_addr_id,

                    "meal_id": meal_id,

                    "belong_model": 600

                    //"time_long_id": time_long_id
                }
            ]
        },

        beforeSend: function (xhr) {

            xhr.setRequestHeader("TOKEN", token);
        },
        success: function (data) {

            if (data.codes == "200") {

                if (isMobile == 1) {

                    var message = {

                        "VcData": {"order_code": data.data.order_code},

                        "VcName": "ListPay",

                        "VcWay": "PushVCName"
                    };

                    window.webkit.messageHandlers.CallManPowerListModel.postMessage(message);

                    //CallManPowerListModel.jsCalliOSWithPushVCName({
                    //
                    //    "VcData": {"order_code": data.data.order_code},
                    //
                    //    "VcName": "ListPay"
                    //});
                } else if (isMobile == 0) {

                    window.android.jumptoOrderActivity(data.data.order_code);

                }
            } else if (data.codes != "200" && data.codes) {

                if (isMobile == 1) {

                    window.webkit.messageHandlers.CallManPowerListModel.postMessage({
                        "VcData": data.msg,
                        "VcWay": "ShowMessage"
                    });

                    //CallManPowerListModel.jsCalliOSWithShowMessage(data.msg);

                } else if (isMobile == 0) {

                    window.android.toastMsg(data.msg);

                }
            } else if (data.codes == null) {

                if (isMobile == 1) {

                    window.webkit.messageHandlers.CallManPowerListModel.postMessage({
                        "VcData": "系统繁忙，请稍后重试",
                        "VcWay": "ShowMessage"
                    });

                    //CallManPowerListModel.jsCalliOSWithShowMessage("系统繁忙，请稍后重试");

                } else if (isMobile == 0) {

                    window.android.toastMsg("系统繁忙，请稍后重试");
                }
            }
        },
        error: function (info) {

            if (isMobile == 1) {

                window.webkit.messageHandlers.CallManPowerListModel.postMessage({
                    "VcData": "请检查网络",
                    "VcWay": "ShowMessage"
                });

                //CallManPowerListModel.jsCalliOSWithShowMessage("请检查网络");

            } else if (isMobile == 0) {

                window.android.toastMsg("请检查网络");
            }
        }
    });
}

//var startDate;
//function receiveiOSOrderStart(a) {//接收ios的参数
//    startDate = $(".order_start").html(a);
//}
//function receive_android_startDate(k) {
//    startDate = $(".order_start").html(k);
//    // alert(k)
//}
//var endDate;
//function receiveiOSOrderEnd(a) {
//    endDate = $(".order_end").html(a);
//}
//function receive_android_endDate(k) {
//    endDate = $(".order_end").html(k);
//}

//开始时间结束时间
//$(".order_time").on("click", ".order_start", function () {
//    if (isMobile == 1) {
//        CallManPowerListModel.jsCalliOSWithStartDate("Start");
//    } else if (isMobile == 0) {
//        window.android.manpowerStartShowToast("ok");
//    }
//});
//$(".order_time").on("click", ".order_end", function () {
//    if (isMobile == 1) {
//        CallManPowerListModel.jsCalliOSWithEndDate("End");
//    } else if (isMobile == 0) {
//        window.android.manpowerEndShowToast("ok");
//    }
//});

